﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCms.Core.Developers;
using MVCms.Core.Entities;
using MVCms.Core.Services;


namespace Plugin.Admin.UploadModule.Controllers
{
    public class ModuleController :BaseController
    {
        [PluginModule(Name = "Upload", Description = "Upload", DisplayName = "Upload")]
        [HttpGet]
        public PartialViewResult Upload()
        {
            return PartialView();
        }

        [HttpPost]
        public ActionResult SaveFile(FormCollection forms)
        {
            foreach (string file in Request.Files)
            {
                var hpf = Request.Files["FileBlob"];
                if (file != null)
                {
                    PersistInfo(hpf);
                }
            }

            return Redirect(Request.UrlReferrer.ToString());
        }

        private bool PersistInfo(HttpPostedFileBase fileBase)
        {
            try
            {
                string savedFileName = Path.Combine(HttpRuntime.BinDirectory, Path.GetFileName(fileBase.FileName));
                fileBase.SaveAs(savedFileName);

                MVCms.Core.Entities.Plugin plugin = new MVCms.Core.Entities.Plugin();
                plugin.Name = Path.GetFileName(fileBase.FileName);
                plugin.PluginModules = PluginService.GetPluginModules(plugin, new FileInfo(savedFileName));

                plugin.Save();
            }
            catch (Exception)
            {

                return false;
            }

            return true;
        }
    }
}
